package com.wushijia.netty;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class MessageUtils {

  //将BaseMessage消息写入ByteBuf
  public static ByteBuf getByteBuf(BaseMessage baseMessage) throws JsonProcessingException {
    byte[] req = new ObjectMapper().writeValueAsBytes(baseMessage);
    ByteBuf bytebuf = Unpooled.buffer();
    bytebuf.writeBytes(req);
    return bytebuf;
  }

  //从ByteBuf中获取信息，使用UTF-8编码后解析为BaseMessage的系统消息格式
  public static BaseMessage getBaseMessage(ByteBuf byteBuf) throws JsonProcessingException {
    byte[] con = new byte[byteBuf.readableBytes()];
    byteBuf.readBytes(con);
    String message = new String(con, StandardCharsets.UTF_8);
    BaseMessage baseMessage = new ObjectMapper().readValue(message, BaseMessage.class);
    baseMessage.setReceiveDate(new Date());
    return baseMessage;
  }
}
